# -*- coding: utf-8 -*-
# File : init_sys_service.py
# Author: taoyahui
# Date : 2021/7/1
import sys
sys.path.append('..')
from fabric import Connection
import logging
from utils import random_util, common_util, path_util
import results
from utils import mysql_util
import sys
from utils.log_util import logger
from tasks import file_distribute
from application_factory.models import InventoryCls
import os
from sys import path

# 获取Hostname
# 入参ip, username, password, port
def get_hostname(ip, username, passwd, port=22):
    """
    获取资产的hostname Service，判断是否需要重置
    :param ip:
    :param username:
    :param passwd:
    :param port:
    :return:
    """
    c = Connection(f"{username}@{ip}", port=port, connect_kwargs={'password': passwd})
    try:
        res = c.run('hostname')
        hostname = res.stdout.strip()
        update_hostname_sql = f"Update inventory set hostname = '{hostname}' where ip = '{ip}'"
        mysql_util.exec_sql_new(update_hostname_sql)

        if hostname == 'localhost.localdomain':
            success_res = common_util.gen_modify_res(200, "ok")
        else:
            success_res = common_util.gen_modify_res(200, "no")
        return success_res
    except Exception as e:
        logger.error(f"get_hostname 错误，原因为: {e}")
        return results.get_hostname_error_result
    finally:
        c.close()


# 设置Hostname
# 入参ip, username, passwd, port, new_hostname(新的主机名)
def set_hostname(ip, username, passwd, port, new_hostname):
    """
    设置资产的Hostname
    :param ip:
    :param username:
    :param passwd:
    :param port:
    :param new_hostname: 新设置的Hostname
    :return:
    """
    c = Connection(f"{username}@{ip}", port=port, connect_kwargs={'password': passwd})
    try:

        res = c.run('cat /etc/redhat-release')
        if "release 6." in res.stdout or "release 5." in res.stdout:
            c.run(f"hostname {new_hostname}")
        else:
            c.run(f'hostnamectl --static set-hostname {new_hostname}')

        # 在数据库中更新
        update_sql = f"Update inventory set hostname = '{new_hostname}' where ip = '{ip}'"
        mysql_util.exec_sql_new(update_sql)
        return results.success_result

        # res = service.linux_inventory_init_configure(inventory_ip=ip, username=username, password=passwd)
        # return res
    except Exception as e:
        logger.error(f"set_hostname 错误，原因为：{e}")
        return results.set_hostname_error_result


# 获取主机的HOSTNAME
def init_hostname(ip, username, passwd, port):
    """
    获取主机的HOSTNAME
    :param ip:
    :param username:
    :param passwd:
    :param port:
    :return:
    """
    c = Connection(f"{username}@{ip}", port=port, connect_kwargs={'password': passwd})
    try:
        res = c.run('hostname')
        if res.stdout.strip() == 'localhost.localdomain':
            new_hostname = 'test' + random_util.random_string()
            c.run(f'hostnamectl --static set-hostname {new_hostname}')
            return new_hostname
        else:
            res = c.run('hostname')
            return res.stdout.strip()
    except Exception as e:
        logger.error(f"init_hostname 错误，原因为 {e}")
    finally:
        c.close()


def update_system_os(ip, set_os):
    find_inventory_sql = f"Select * from inventory where ip = '{ip}' limit 1"
    res = mysql_util.exec_sql_new(find_inventory_sql)
    if res is not None and len(res) > 0:
        inventory_res = res[0]
        inventory = InventoryCls(inventory_res)
        if inventory.os is None or inventory.os == '未知':
            update_sql = f"Update inventory set os = '{set_os}' where ip = '{ip}'"
            mysql_util.exec_sql_new(update_sql)


def usability_detect(ip, username, passwd, port):
    """
    资产可用性探测Service
    :param ip:
    :param username:
    :param passwd:
    :param port:
    :return:
    """
    c = Connection(f"{username}@{ip}", port=port, connect_kwargs={'password': passwd})
    try:
        res = c.run('hostname')

        update_sql = f"Update inventory set is_available = 1, username = '{username}', password = '{passwd}', " \
                     f"host_port = '{port}', hostname= '{res.stdout.strip()}' where ip = '{ip}'"
        mysql_util.exec_sql_new(update_sql)
        update_system_os(ip, 'linux')
        return results.success_result
    except Exception as e:
        logger.error(f"无法检测到主机: IP is {ip}, Error is : {e}")
        return results.inventory_unavailable_result


def win_usability_detect(ip, username, passwd, port):
    """
    Windows 可用性探测
    :param ip:
    :param username:
    :param passwd:
    :param port:
    :return:
    """
    touch_file = os.path.join(path_util.get_root_dir(), "touch_file")
    os.system(f"touch {touch_file}")
    inventory = InventoryCls()
    inventory.set_ip(ip)
    inventory.set_username(username)
    inventory.set_password(passwd)
    inventory.set_port(port)
    print(inventory.__dict__)
    copy_res = file_distribute.copy_source(touch_file, 'detect', [inventory])
    if int(copy_res) == 0:
        logger.info(f"win_usability_detect -> Detect success! ip is {ip}")
        update_sql = f"Update inventory set is_available = 1, username = '{username}', password = '{passwd}', " \
                     f"host_port = '{port}' where ip = '{ip}'"
        mysql_util.exec_sql_new(update_sql)

        # 设置机器操作系统为windows
        update_system_os(ip, 'windows')
        return results.success_result
    else:
        logger.error(f"win_usability_detect -> Can't Detect: IP is {ip}")
        return results.inventory_unavailable_result


if __name__ == '__main__':
    win_usability_detect('192.168.50.219', 'adminer', '123456', 5985)